#include "socket_config.h"
//#include "flash_helper.h"  // 你封装的 flash 读写函数
#include "Drv_W25Q64.h"  // 你自定义的 Flash 读写封装
#include <string.h>
#include <stdio.h>

#define SOCKET_CONFIG_MAGIC 0x53434F4E  // 'SCON' 魔术字校验

typedef struct
{
    uint32_t magic;
    SocketConfig_TypeDef config_array[SOCKET_CONFIG_COUNT];
    uint32_t crc;  // 简单校验用
} SocketConfigFlashWrap;

SocketConfig_TypeDef local_socket_config[SOCKET_CONFIG_COUNT];

static uint32_t simple_crc32(uint8_t* data, uint32_t length)
{
    uint32_t crc = 0;
    for(uint32_t i = 0; i < length; i++)
    {
        crc += data[i];
    }
    return crc;
}

void LoadSocketConfigFromFlash(void)
{
    SocketConfigFlashWrap wrap;
    //Flash_Read(SOCKET_CONFIG_ADDRESS, (uint8_t*)&wrap, sizeof(wrap));
	  W25Q64_ReadData(SOCKET_CONFIG_ADDRESS, (uint8_t *)&wrap, sizeof(wrap));  

    if (wrap.magic == SOCKET_CONFIG_MAGIC)
    {
			  printf("=== Socket Config Load from FLash magic is %08X ===\r\n",wrap.magic );
        uint32_t crc = simple_crc32((uint8_t*)&wrap.config_array, sizeof(local_socket_config));
			  printf("=== Socket Config Load from FLash crc is %d ===\r\n",wrap.crc );
				printf("=== Socket Config jisuan crc is %d ===\r\n",crc );
        if (crc == wrap.crc)
        {
					  printf("=== Socket Config Loaded from Flash ===\r\n");
            //local_socket_config = wrap.config;
					  memcpy(local_socket_config, wrap.config_array, sizeof(local_socket_config));
            return;
        }
    }

    // 无效数据，恢复默认
    ResetSocketConfigToDefault();
}

void SaveSocketConfigToFlash(void)
{
    SocketConfigFlashWrap wrap;
    wrap.magic = SOCKET_CONFIG_MAGIC;
    //wrap.config = local_socket_config;
	  memcpy(wrap.config_array, local_socket_config, sizeof(local_socket_config));
    wrap.crc = simple_crc32((uint8_t*)&wrap.config_array, sizeof(local_socket_config));
	  printf("=== Socket Config save crc is %d ===\r\n",wrap.crc ); 
	  W25Q64_SectorErase(SOCKET_CONFIG_ADDRESS);	
    W25Q64_PageProgram(SOCKET_CONFIG_ADDRESS, (uint8_t*)&wrap, sizeof(wrap)); 
}

void ResetSocketConfigToDefault(void)
{
    for (int i = 0; i < SOCKET_CONFIG_COUNT; ++i)
    {
        local_socket_config[i].mode = SOCKET_MODE_CLIENT;
        local_socket_config[i].server_ip[0] = 192;
        local_socket_config[i].server_ip[1] = 168;
        local_socket_config[i].server_ip[2] = 0;
        local_socket_config[i].server_ip[3] = 253;
        local_socket_config[i].server_port = 40004;
        local_socket_config[i].localport = 5000 + i;
    }
		printf("=== Socket Config set Default %d===\r\n",local_socket_config[5].localport );
		SaveSocketConfigToFlash();
}


